package zj.it.bhne.gridengineeringsurvey.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import zj.it.bhne.gridengineeringsurvey.BaseActivity;
import zj.it.bhne.gridengineeringsurvey.MyApplication;
import zj.it.bhne.gridengineeringsurvey.R;
import zj.it.bhne.gridengineeringsurvey.fragment.OneFragment;
import zj.it.bhne.gridengineeringsurvey.fragment.ThreeFragment;
import zj.it.bhne.gridengineeringsurvey.fragment.TwoFragment;
import zj.it.bhne.gridengineeringsurvey.myutils.AndroidWorkaround;

/**
 * 进入应用主页活动
 */
public class BottomActivity extends BaseActivity implements View.OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback {

    private static final int num = 123;//用于验证获取的权
    private TextView bottom_tv_title;
    private long exitTime = 0;
    private TextView[] textViews;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint({"RestrictedApi", "ResourceAsColor"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bottom);
        //为了底部有虚拟按键的优化
        if (AndroidWorkaround.checkDeviceHasNavigationBar(this)) {
            AndroidWorkaround.assistActivity(findViewById(android.R.id.content));
        }
        requireSomePermission();// 申请权限
        initView();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);//设置toolbar


        //获取intent值，通过判断值确定跳转到哪个fragment
        Intent intent = getIntent();
        int one = intent.getIntExtra("item_id", 0);
        switch (one) {
            case 2:
                setColor(1);
                bottom_tv_title.setText(getString(R.string.bottom_two));
                break;
            case 3:
                setColor(2);
                bottom_tv_title.setText(getString(R.string.bottom_three));
                fragmentManger(new ThreeFragment());
                break;
            default:
                fragmentManger(new OneFragment());
                break;
        }
    }

    /**
     * 实现底部导航栏的切换。
     *
     * @param i 传入按钮的序号
     */
    private void setColor(int i) {
        for (int j = 0; j < 3; j++) {
            if (i == j) {
                textViews[j].setTextColor(Color.rgb(18, 150, 219));
                textViews[j].setSelected(true);
            } else {
                textViews[j].setTextColor(Color.BLACK);
                textViews[j].setSelected(false);
            }
        }
    }

    /**
     * 初始化视图
     */
    private void initView() {
        bottom_tv_title = findViewById(R.id.bottom_tv_title);
        bottom_tv_title.setOnClickListener(this);
        textViews = new TextView[]{findViewById(R.id.bottom_btn_one), findViewById(R.id.bottom_btn_two), findViewById(R.id.bottom_btn_three)};
        for (TextView textView : textViews) {
            textView.setOnClickListener(this);
        }
        setColor(0);
    }

    /**
     * 实现按钮的点击事件
     */
    @SuppressLint("ResourceAsColor")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bottom_btn_one:
                fragmentManger(new OneFragment());
                setColor(0);
                bottom_tv_title.setText(getString(R.string.app_name));
                break;
            case R.id.bottom_btn_two:
                fragmentManger(new TwoFragment());
                setColor(1);
                bottom_tv_title.setText(getString(R.string.bottom_two));
                break;
            case R.id.bottom_btn_three:
                fragmentManger(new ThreeFragment());
                setColor(2);
                bottom_tv_title.setText(getString(R.string.bottom_three));
                break;
        }
    }


    /**
     * fragment的切换
     */
    private void fragmentManger(Fragment fragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.content, fragment);
        transaction.commit();
    }


    /**
     * 通过第三方插件easyPermissions来管理权限问题
     */
    @AfterPermissionGranted(num)
    private void requireSomePermission() {
        String[] perms = {
                // 把你想要申请的权限放进这里就行，注意用逗号隔开
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.VIBRATE,
                Manifest.permission.WAKE_LOCK,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.INTERNET,
                Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
                Manifest.permission.READ_LOGS,
                Manifest.permission.WRITE_SETTINGS
        };
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Already have permission, do the thing
            // ...
            //Toast.makeText(this, "Permissions Granted!", Toast.LENGTH_LONG).show();
            //Log.e("TAG", "requireSomePermission:   Permissions Granted!");
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。",
                    num, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
            SPUtils.getInstance().put("update","0");

        } else {
           /* for (int i = 0; i < MyApplication.activityList.size(); i++) {
                MyApplication.activityList.get(i).finish();
            }*/
            MyApplication.getInstances().exit();
        }
    }
}
